package fit.conceptmap.controller;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import fit.conceptmap.beans.AssignmentBean;
import fit.conceptmap.beans.JsonBean;
import fit.conceptmap.services.IAssignmentService;
import fit.conceptmap.services.IDrawService;
import fit.conceptmap.utils.DrawUtils;

@Controller
@SessionAttributes({"username", "role" })
public class AssignmentController {
	
	@Autowired
	IAssignmentService assignmentService;
	@Autowired
	IDrawService drawService;
	
	@RequestMapping(value="/addAssignment", method=RequestMethod.POST, headers="Accept=application/json")
	@ResponseBody
	public AssignmentBean draw(@RequestBody AssignmentBean json, Model model, 
			@ModelAttribute("username") String username) throws ParseException {
		AssignmentBean assignment = json;
		assignment.setOwner(username);
		assignment.setIdAssignment(assignment.getName() + "_" + DrawUtils.random());
		assignmentService.createAssignment(assignment);
		assignmentService.createMemberAssignment(assignment.getIdMember(), assignment);
		return assignment;
	}
	
	/**
	 * Go exercise 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/exercise", method = RequestMethod.GET)
	public String goExercise(Model model, @ModelAttribute("username") String username) {
		return "exercise";
	}
	
	@RequestMapping(value = "/listexercise", method = RequestMethod.GET, headers="Accept=application/json")
	@ResponseBody
	public List<JsonBean> goListExercise(Model model, @ModelAttribute("username") String username) {
		return assignmentService.getListExercise(username);
	}
	
	/**
	 * Load concept maps
	 * Remove all relation ship 
	 * @param model
	 * @param conceptMapsId
	 * @return
	 */
	@RequestMapping(value="/loadconceptmapForExercise/{conceptMapsId}", method=RequestMethod.GET)
	@ResponseBody
	public HashMap<String, Object> loadDraw(Model model, 
			@PathVariable String conceptMapsId,
			@ModelAttribute("username") String username) {
		HashMap<String, Object> result = new HashMap<String, Object>();
		JsonBean jsonBean = drawService.getJsonBean(conceptMapsId);
		jsonBean.setLinkDataArray(null);
		result.put("jsonBean", jsonBean);
		result.put("assignmentInfo", assignmentService.getInfoAssignmentByConceptMapsId(username, conceptMapsId));
		return result;
	}
}
